import { defineStore } from 'pinia';
import axios from 'axios';

export const useRecommendationStore = defineStore('recommendation', {
  state: () => ({
    recommendations: {
      healthBased: [],
      tasteBased: [],
      preferenceBased: [],
      random: []
    },
    similarRecipes: {},
    lastFetchTimes: {},
    cacheDuration: 5 * 60 * 1000, // 缓存有效期，默认5分钟
    loading: false,
    error: null
  }),

  actions: {
    // 获取个性化推荐
    async fetchPersonalizedRecommendations(userId, limit = 5) {
      if (!userId) return;
      
      const cacheKey = `personalized-${userId}-${limit}`;
      const now = Date.now();
      
      // 如果有缓存且未过期，直接返回缓存
      if (
        this.lastFetchTimes[cacheKey] && 
        now - this.lastFetchTimes[cacheKey] < this.cacheDuration
      ) {
        return this.recommendations;
      }
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await axios.get(`/api/recommendation/personalized?userId=${userId}&limit=${limit}`);
        
        if (response.data.code === 200) {
          // 更新缓存
          this.recommendations = response.data.data;
          this.lastFetchTimes[cacheKey] = now;
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取推荐失败');
        }
      } catch (error) {
        console.error('获取个性化推荐失败:', error);
        this.error = error.message || '获取个性化推荐失败';
        return {};
      } finally {
        this.loading = false;
      }
    },

    // 获取健康导向的推荐
    async fetchHealthBasedRecommendations(userId, limit = 10) {
      if (!userId) return [];
      
      const cacheKey = `health-${userId}-${limit}`;
      const now = Date.now();
      
      // 如果有缓存且未过期，直接返回缓存
      if (
        this.recommendations.healthBased?.length > 0 && 
        this.lastFetchTimes[cacheKey] && 
        now - this.lastFetchTimes[cacheKey] < this.cacheDuration
      ) {
        return this.recommendations.healthBased;
      }
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await axios.get(`/api/recommendation/health?userId=${userId}&limit=${limit}`);
        
        if (response.data.code === 200) {
          // 更新缓存
          this.recommendations.healthBased = response.data.data;
          this.lastFetchTimes[cacheKey] = now;
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取推荐失败');
        }
      } catch (error) {
        console.error('获取健康推荐失败:', error);
        this.error = error.message || '获取健康推荐失败';
        return [];
      } finally {
        this.loading = false;
      }
    },

    // 获取口味导向的推荐
    async fetchTasteBasedRecommendations(userId, limit = 10) {
      if (!userId) return [];
      
      const cacheKey = `taste-${userId}-${limit}`;
      const now = Date.now();
      
      // 如果有缓存且未过期，直接返回缓存
      if (
        this.recommendations.tasteBased?.length > 0 && 
        this.lastFetchTimes[cacheKey] && 
        now - this.lastFetchTimes[cacheKey] < this.cacheDuration
      ) {
        return this.recommendations.tasteBased;
      }
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await axios.get(`/api/recommendation/taste?userId=${userId}&limit=${limit}`);
        
        if (response.data.code === 200) {
          // 更新缓存
          this.recommendations.tasteBased = response.data.data;
          this.lastFetchTimes[cacheKey] = now;
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取推荐失败');
        }
      } catch (error) {
        console.error('获取口味推荐失败:', error);
        this.error = error.message || '获取口味推荐失败';
        return [];
      } finally {
        this.loading = false;
      }
    },

    // 获取偏好导向的推荐
    async fetchPreferenceBasedRecommendations(userId, limit = 10) {
      if (!userId) return [];
      
      const cacheKey = `preference-${userId}-${limit}`;
      const now = Date.now();
      
      // 如果有缓存且未过期，直接返回缓存
      if (
        this.recommendations.preferenceBased?.length > 0 && 
        this.lastFetchTimes[cacheKey] && 
        now - this.lastFetchTimes[cacheKey] < this.cacheDuration
      ) {
        return this.recommendations.preferenceBased;
      }
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await axios.get(`/api/recommendation/preference?userId=${userId}&limit=${limit}`);
        
        if (response.data.code === 200) {
          // 更新缓存
          this.recommendations.preferenceBased = response.data.data;
          this.lastFetchTimes[cacheKey] = now;
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取推荐失败');
        }
      } catch (error) {
        console.error('获取偏好推荐失败:', error);
        this.error = error.message || '获取偏好推荐失败';
        return [];
      } finally {
        this.loading = false;
      }
    },

    // 获取相似食谱推荐
    async fetchSimilarRecipes(recipeId, userId, limit = 10) {
      if (!recipeId) return [];
      
      const cacheKey = `similar-${recipeId}-${limit}`;
      const now = Date.now();
      
      // 如果有缓存且未过期，直接返回缓存
      if (
        this.similarRecipes[recipeId]?.length > 0 && 
        this.lastFetchTimes[cacheKey] && 
        now - this.lastFetchTimes[cacheKey] < this.cacheDuration
      ) {
        return this.similarRecipes[recipeId];
      }
      
      this.loading = true;
      this.error = null;
      
      try {
        const url = userId
          ? `/api/recommendation/similar/${recipeId}?userId=${userId}&limit=${limit}`
          : `/api/recommendation/similar/${recipeId}?limit=${limit}`;
          
        const response = await axios.get(url);
        
        if (response.data.code === 200) {
          // 更新缓存
          this.similarRecipes[recipeId] = response.data.data;
          this.lastFetchTimes[cacheKey] = now;
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取推荐失败');
        }
      } catch (error) {
        console.error('获取相似食谱失败:', error);
        this.error = error.message || '获取相似食谱失败';
        return [];
      } finally {
        this.loading = false;
      }
    },

    // 记录推荐点击
    async recordRecommendationClick(id) {
      if (!id) return false;
      
      try {
        const response = await axios.post(`/api/recommendation/click/${id}`);
        return response.data.code === 200;
      } catch (error) {
        console.error('记录推荐点击失败:', error);
        return false;
      }
    },

    // 提交推荐反馈
    async submitRecommendationFeedback(id, feedback) {
      if (!id || !feedback) return false;
      
      try {
        const response = await axios.post(`/api/recommendation/feedback/${id}?feedback=${feedback}`);
        return response.data.code === 200;
      } catch (error) {
        console.error('提交推荐反馈失败:', error);
        return false;
      }
    },

    // 清除特定缓存
    clearCache(type, id, limit) {
      if (type && id) {
        const cacheKey = `${type}-${id}-${limit || 10}`;
        delete this.lastFetchTimes[cacheKey];
        
        if (type === 'similar') {
          delete this.similarRecipes[id];
        } else {
          this.recommendations[`${type}Based`] = [];
        }
      }
    },

    // 清除所有缓存
    clearAllCache() {
      this.recommendations = {
        healthBased: [],
        tasteBased: [],
        preferenceBased: [],
        random: []
      };
      this.similarRecipes = {};
      this.lastFetchTimes = {};
    }
  },
  
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'recommendation-store',
        storage: localStorage,
        paths: ['recommendations', 'similarRecipes', 'lastFetchTimes']
      }
    ]
  }
}); 